<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">

      <el-form-item label="用户id" prop="userId">
        <el-input v-model="queryParams.userId" placeholder="请输入用户id" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="手机号" prop="username">
        <el-input v-model="queryParams.username" placeholder="手机号" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <!-- <el-form-item label="年龄" prop="age">
        <el-input v-model="queryParams.age" placeholder="请输入年龄" clearable @keyup.enter.native="handleQuery" />
      </el-form-item> -->
      <el-form-item label="性别" prop="gender">
        <el-input v-model="queryParams.gender" placeholder="请输入性别" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="身份证" prop="idCard">
        <el-input v-model="queryParams.idCard" placeholder="请输入身份证" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <!-- <el-form-item label="邀请码" prop="invitationCode">
        <el-input v-model="queryParams.invitationCode" placeholder="请输入邀请码" clearable
          @keyup.enter.native="handleQuery" />
      </el-form-item> -->
      <el-form-item label="所在地址" prop="address">
        <el-input v-model="queryParams.address" placeholder="请输入所在地址" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="邀请人id" prop="inviterId">
        <el-input v-model="queryParams.inviterId" placeholder="请输入邀请人id" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
        >新增
        </el-button>
      </el-col>
      <!--      <el-col :span="1.5">-->
      <!--        <el-button-->
      <!--          type="success"-->
      <!--          plain-->
      <!--          icon="el-icon-edit"-->
      <!--          size="mini"-->
      <!--          :disabled="single"-->
      <!--          @click="handleUpdate"-->
      <!--          v-hasPermi="['system:user:edit']"-->
      <!--        >修改</el-button>-->
      <!--      </el-col>-->
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
        >
          删除
        </el-button>
      </el-col>
      <!--      <el-col :span="1.5">-->
      <!--        <el-button-->
      <!--          type="warning"-->
      <!--          plain-->
      <!--          icon="el-icon-download"-->
      <!--          size="mini"-->
      <!--          @click="handleExport"-->
      <!--          v-hasPermi="['system:user:export']"-->
      <!--        >导出</el-button>-->
      <!--      </el-col>-->
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="userList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" width="50" type="index" align="center" prop="id" />

      <el-table-column label="用户信息" align="center" width="220">
        <template slot-scope="scope">
          <div>{{scope.row.username}}</div>
          <div>{{scope.row.userId}}</div>
          <div>{{scope.row.phone}}</div>
          <div>{{scope.row.age}}</div>
        </template>
      </el-table-column>

      <!-- <el-table-column label="姓名" align="center" prop="name" />
      <el-table-column label="手机号" align="center" prop="phone" />
      <el-table-column label="年龄" align="center" prop="age" /> -->

      <el-table-column label="姓名" align="center" prop="name" />
      <el-table-column label="性别" align="center" prop="gender" />
      <el-table-column label="身份证" align="center" prop="idCard" />
      <el-table-column label="邀请码" align="center" prop="invitationCode" />
      <el-table-column label="所在地址" align="center" prop="address" />
      <el-table-column label="昵称" align="center" prop="nickname" />
      <el-table-column label="邀请人ID" align="center" prop="inviterId" />
      <el-table-column label="创建时间" align="center" prop="createTime" />
      <!--      <el-table-column label="工作经历" align="center" prop="workExperience"/>-->
      <el-table-column label="工作经历" align="center" prop="workExperience" width="400">
        <template slot-scope="scope">
          <div
            v-if="scope.row.workExperience"
            style="display: flex; flex-wrap: wrap; align-items: center; justify-content: center;"
          >
            <template v-for="(item, index) in parseFiles(scope.row.workExperience)">
              <template v-if="isImage(item)">
                <!-- 是图片就预览 -->
                <image-preview
                  :src="scope.row.workExperience"
                  :width="50"
                  :height="50"
                  :key="`img-${index}`"
                />
              </template>
              <template v-else>
                <!-- 非图片，显示链接 -->
                <a
                  :href="getFileName(item)"
                  target="_blank"
                  style="margin: 0 5px;"
                  :key="`link-${index}`"
                >
                  文件{{ index + 1 }}
                </a>
              </template>

              <!-- 添加分隔符 -->
              <span v-if="index !== parseFiles(scope.row.workExperience).length - 1" style="margin: 0 5px;">|</span>
            </template>
          </div>
        </template>
      </el-table-column>

      <el-table-column label="是否可用, 0-正常, 1-禁用" align="center" prop="userStatus" :formatter="formatUserStatus" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleAll(scope.row)">详情
          </el-button>
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)">修改
          </el-button>
          <el-button size="mini" type="text" :icon="scope.row.userStatus === '0' ? 'el-icon-close' : 'el-icon-check'"
            @click="handleToggleStatus(scope.row)">
            {{ scope.row.userStatus === '0' ? '禁用' : '启用' }}
          </el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改【请填写功能名称】对话框 -->
    <el-dialog :title="title" :visible.sync="open2" width="1000px" append-to-body>
      <div class="dialog-body">
        <el-form ref="form" :model="form" :rules="rules" label-width="100px">
          <el-row>
            <el-col :span="24">
              <el-divider></el-divider>
              <div class="form-section-title">工作经历</div>
              <div class="scroll-area">
                <el-table :data="form.workExperiences" border v-if="form.workExperiences && form.workExperiences.length">
                  <el-table-column prop="startTime" label="开始日期" align="center" />
                  <el-table-column prop="endTime" label="结束日期" align="center" />
                  <el-table-column prop="companyName" label="公司名称" align="center" />
                  <el-table-column prop="product" label="负责产品" align="center" />
                  <el-table-column prop="hospitalName" label="医院名称" align="center" />
                  <el-table-column prop="department" label="科室" align="center" />
                </el-table>
                <div v-else>暂无数据</div>
              </div>
            </el-col>
          </el-row>

          <el-row class="equal-columns">
            <el-col class="col-left" :span="12">
              <el-divider></el-divider>
              <div class="col-content">
                <!-- 左侧内容 -->
                <el-form-item label="简历" prop="workExperience">
                  <div v-for="(item, index) in splitWorkExperience" :key="index" style="margin-bottom: 8px;">
                    <template v-if="isImage(item)">
                      <image-preview :src="item" :width="60" :height="60" />
                    </template>
                    <template v-else>
                      <el-link :href="getFileName(item)" target="_blank">文件{{ index + 1 }}</el-link>
                    </template>
                  </div>
                </el-form-item>

<!--                <el-divider></el-divider>-->
<!--                <div class="form-section-title">工作经历</div>-->
<!--                <div class="scroll-area">-->
<!--                  <el-table :data="form.workExperiences" border v-if="form.workExperiences && form.workExperiences.length">-->
<!--                    <el-table-column prop="startTime" label="开始日期" align="center" />-->
<!--                    <el-table-column prop="endTime" label="结束日期" align="center" />-->
<!--                    <el-table-column prop="companyName" label="公司名称" align="center" />-->
<!--                    <el-table-column prop="product" label="负责产品" align="center" />-->
<!--                    <el-table-column prop="hospitalName" label="医院名称" align="center" />-->
<!--                    <el-table-column prop="department" label="科室" align="center" />-->
<!--                  </el-table>-->
<!--                  <div v-else>暂无数据</div>-->
<!--                </div>-->

                <el-divider></el-divider>
                <div class="form-section-title">病种</div>
                <div class="scroll-area" style="height: 600px">
                  <el-table :data="form.diseaseList" border v-if="form.diseaseList && form.diseaseList.length">
                    <el-table-column prop="illnessName" label="病种" align="center" />
                    <el-table-column prop="synopsis" label="简介" align="center" />
                    <el-table-column prop="price" label="价格" align="center" />
                  </el-table>
                  <div v-else>暂无数据</div>
                </div>

                <el-divider></el-divider>
                <div class="form-section-title">我的团队</div>
                <el-tabs v-model="activeTab">
                  <el-tab-pane label="专家" name="doctor">
                    <div class="scroll-area">
                      <el-table :data="form.expertList" border v-if="form.expertList && form.expertList.length">
                        <el-table-column prop="userId" label="ID" align="center" />
                        <el-table-column prop="name" label="姓名" align="center" />
                      </el-table>
                      <div v-else>暂无数据</div>
                    </div>
                  </el-tab-pane>

                  <el-tab-pane label="用户" name="user">
                    <div class="scroll-area">
                      <el-table :data="form.iuserList" border v-if="form.iuserList && form.iuserList.length">
                        <el-table-column prop="userId" label="ID" align="center" />
                        <el-table-column prop="nickname" label="昵称" align="center" />
                      </el-table>
                      <div v-else>暂无数据</div>
                    </div>
                  </el-tab-pane>
                </el-tabs>
              </div>
            </el-col>

            <el-col class="col-right" :span="12">
              <el-divider></el-divider>
              <div class="col-content">
                <!-- 右侧内容 -->
                <el-row>
                  <el-col :span="12">
                    <el-form-item label="金豆总数">{{form.ddTotalNumber}}</el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="专家总收益">{{form.totalAmount}}</el-form-item>
                  </el-col>
                </el-row>

                <el-divider></el-divider>
                <div class="form-section-title">金豆收益</div>
                <div class="scroll-area" style="height: 600px">
                  <el-table :data="form.ddDetailsList" border v-if="form.ddDetailsList && form.ddDetailsList.length">
                    <el-table-column prop="source" label="来源" align="center" />
                    <el-table-column prop="details" label="收支" align="center" />
                    <el-table-column prop="createTime" label="时间" align="center" />
                  </el-table>
                  <div v-else>暂无数据</div>
                </div>

                <el-divider></el-divider>
                <div class="form-section-title">收益</div>
                <div class="scroll-area">
                  <el-table :data="form.incomeList" border v-if="form.incomeList && form.incomeList.length">
                    <el-table-column prop="source" label="来源" align="center" />
                    <el-table-column prop="incomeDetails" label="收支" align="center" />
                    <el-table-column prop="createTime" label="时间" align="center" />
                  </el-table>
                  <div v-else>暂无数据</div>
                </div>
              </div>
            </el-col>
          </el-row>
        </el-form>
      </div>
    </el-dialog>


    <el-dialog :title="title" :visible.sync="open1" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="新密码" prop="password">
          <el-input v-model="password" placeholder="新密码" />
        </el-form-item>
      </el-form>
      <div>
        <el-button type="primary" @click="updatePassword">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 添加或修改【请填写功能名称】对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="手机号" prop="username">
          <el-input v-model="form.username" placeholder="请输入手机号" />
        </el-form-item>
<!--        <el-form-item label="姓名" prop="name">-->
<!--          <el-input v-model="form.name" placeholder="请输入姓名" />-->
<!--        </el-form-item>-->
<!--        <el-form-item label="年龄" prop="age">-->
<!--          <el-input v-model="form.age" placeholder="请输入年龄" />-->
<!--        </el-form-item>-->
<!--        <el-form-item label="性别" prop="gender">-->
<!--          <el-input v-model="form.gender" placeholder="请输入性别" />-->
<!--        </el-form-item>-->
<!--        <el-form-item label="身份证" prop="idCard">-->
<!--          <el-input v-model="form.idCard" placeholder="请输入身份证" />-->
<!--        </el-form-item>-->
        <el-form-item label="密码" prop="password">
          <el-input v-model="form.password" placeholder="请输入密码" />
        </el-form-item>
        <!--        <el-form-item label="头像" prop="imageAddress">-->
        <!--          <el-input v-model="form.imageAddress" placeholder="请输入头像"/>-->
        <!--        </el-form-item>-->
<!--        <el-form-item label="头像" prop="imageAddress">-->
<!--          <image-upload v-model="form.imageAddress" />-->
<!--        </el-form-item>-->
<!--        <el-form-item label="是否是专家, 是, 否" prop="isExpert">-->
<!--          <el-input v-model="form.isExpert" placeholder="请输入是否是专家, 是, 否" />-->
<!--        </el-form-item>-->
<!--        <el-form-item label="所在地址" prop="address">-->
<!--          <el-input v-model="form.address" placeholder="请输入所在地址" />-->
<!--        </el-form-item>-->
<!--        <el-form-item label="是否公立, 是, 不是, 不限" prop="isPublic">-->
<!--          <el-input v-model="form.isPublic" placeholder="请输入是否公立, 是, 不是, 不限" />-->
<!--        </el-form-item>-->
<!--        <el-form-item label="昵称" prop="nickname">-->
<!--          <el-input v-model="form.nickname" placeholder="请输入昵称" />-->
<!--        </el-form-item>-->
        <el-form-item label="邀请人id" prop="inviterId">
          <el-input v-model="form.inviterId" placeholder="请输入邀请人id" />
        </el-form-item>
<!--        <el-form-item label="工作经历" prop="workExperience">-->
<!--          <el-input v-model="form.workExperience" placeholder="请输入工作经历"/>-->
<!--        </el-form-item>-->
<!--        <el-form-item label="工作经历" prop="workExperience">-->
<!--          <image-preview :src="form.workExperience" :width="60" :height="60" />-->
<!--        </el-form-item>-->

<!--        <el-form-item label="病种" prop="diseaseIds">-->
<!--          <el-select v-model="form.diseaseIds" multiple placeholder="请选择病种" clearable collapse-tags-->
<!--            collapse-tags-tooltip style="width: 100%;">-->
<!--            <el-option v-for="item in diseases" :key="item.diseaseId" :label="item.illnessName" :value="item.diseaseId">-->
<!--            </el-option>-->
<!--          </el-select>-->
<!--        </el-form-item>-->
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listUser, getUser, delUser, addUser, updateUser, updatePassword } from "@/api/expert/expert"
import { listDisease } from "@/api/disease/disease"
export default {
  name: "User",
  data() {
    return {
      activeTab: 'doctor',
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      open1: false,
      open2: false,
      // 【请填写功能名称】表格数据
      userList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        userId: null,
        username: null,
        name: null,
        age: null,
        gender: null,
        idCard: null,
        invitationCode: null,
        password: null,
        imageAddress: null,
        isExpert: null,
        address: null,
        isPublic: null,
        nickname: null,
        inviterId: null,
        workExperience: null,
        userStatus: null,
        processStatus: null,
        ddTotalNumber: null,
        totalAmount: null,
        diseaseIds: []
      },
      // 表单参数
      form: {
        incomeList: [],
        ddDetailsList: [],
        iuserList: [],
        expertList: [],
        diseaseList: [],
        diseaseIds: []
      },
      diseases: [],
      password: null,
      // 表单校验
      rules: {
        username: [
          { required: true, message: "手机号不能为空", trigger: "blur" }
        ],
        password: [
          { required: true, message: "密码不能为空", trigger: "blur" }
        ],
      }
    }
  },
  created() {
    this.getList()
  },
  computed: {
    splitWorkExperience() {
      if (!this.form.workExperience) return [];
      return this.form.workExperience.split(',').map(s => s.trim()).filter(Boolean);
    }
  },
  methods: {
    parseFiles(value) {
      if (!value) return [];
      return value.split(',').map(item => item.trim());
    },
    isImage(url) {
      return /\.(png|jpe?g|gif|bmp|webp)$/i.test(url);
    },
    getFileName(url) {
      console.log(url)
      return process.env.VUE_APP_BASE_API + url
    },
    formatUserStatus(row, column, cellValue) {
      return cellValue === '0' ? '正常' : '禁用';
    },
    handleToggleStatus(row) {
      console.log(row);
      // 根据当前状态切换
      if (row.userStatus === '0') {
        // 执行禁用操作
        row.userStatus = '1';  // 更新为禁用状态
        updateUser(row).then(response => {
          this.getList()
        })
        this.$message.success('已禁用');
      } else {
        // 执行启用操作
        row.userStatus = '0';  // 更新为启用状态
        updateUser(row).then(response => {
          this.getList()
        })
        this.$message.success('已启用');
      }
    },
    /** 查询【请填写功能名称】列表 */
    getList() {
      this.loading = true
      this.queryParams.isExpert = 0
      this.queryParams.processStatus = 0
      listUser(this.queryParams).then(response => {
        this.userList = response.rows
        this.total = response.total
        this.loading = false
      })
    }
    ,
    // 取消按钮
    cancel() {
      this.open = false
      this.open1 = false
      this.open2 = false
      this.reset()
    }
    ,
    // 表单重置
    reset() {
      this.form = {
        id: null,
        userId: null,
        username: null,
        name: null,
        age: null,
        gender: null,
        idCard: null,
        invitationCode: null,
        password: null,
        imageAddress: null,
        isExpert: null,
        address: null,
        isPublic: null,
        nickname: null,
        inviterId: null,
        workExperience: null,
        createTime: null,
        userStatus: null,
        processStatus: null,
        ddTotalNumber: null,
        totalAmount: null
      }
      this.resetForm("form")
    }
    ,
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    }
    ,
    updatePassword() {
      this.form.password = this.password
      updatePassword(this.form).then(response => {
        this.$modal.msgSuccess("修改成功")
        this.open1 = false
      })
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm")
      this.handleQuery()
    }
    ,
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    }
    ,
    /** 新增按钮操作 */
    handleAdd() {
      this.diseases = []
      listDisease().then(response => {
        console.log(1111, response.rows)
        this.diseases = response.rows
      })
      this.reset()
      this.open = true
      this.title = "添加【专家信息】"
    }
    ,
    handleAll(row) {
      this.reset()
      const id = row.id || this.ids
      getUser(id).then(response => {
        this.form = response.data
        this.open2 = true
        this.title = "【详情】"
      })
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids
      getUser(id).then(response => {
        this.form = response.data
        this.open1 = true
        this.title = "修改密码"
      })
    }
    ,
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateUser(this.form).then(response => {
              this.$modal.msgSuccess("修改成功")
              this.open = false
              this.getList()
            })
          } else {
            // const isPublic = this.form.isPublic;
            // if (isPublic === '是') {
            //   this.form.isPublic = 0;
            // } else if (isPublic === '否') {
            //   this.form.isPublic = 1;
            // } else if (isPublic === '不限') {
            //   this.form.isPublic = 2;
            //   // 可选：这里可以加一个 else 处理其他情况
            // }
            //
            // const isExpert = this.form.isExpert;
            // if (isExpert === '是') {
            //   this.form.isExpert = 0;
            // } else if (isExpert === '否') {
            //   this.form.isExpert = 1;
            //   // 可选：这里可以加一个 else 处理其他情况
            // }
            addUser(this.form).then(response => {
              const result = response.data
              if (result === 0) {
                this.$modal.msgError("用户名已存在")
              } else {
                this.$modal.msgSuccess("新增成功")
                this.open = false
                this.getList()
              }
            })

          }
        }
      })
    }
    ,
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$modal.confirm('是否确认删除【专家】编号为"' + ids + '"的数据项？').then(function () {
        return delUser(ids)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {
      })
    }
    ,
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/user/export', {
        ...this.queryParams
      }, `user_${new Date().getTime()}.xlsx`)
    }
  }
}
</script>

<style lang="scss" scoped>
.col-left {
  padding-right: 20px;
}
.equal-columns {
  display: flex;
  align-items: stretch;
}
.col-content {
  display: flex;
  flex-direction: column;
  height: 100%;
}
.scroll-area {
  max-height: 200px;
  overflow-y: auto;
}
</style>
